import urllib.request as ur
import urllib.parse as up
from http import cookiejar
import string
import re

from setting_lc import login_encode_type4,parseUeage
from setting_lc import INIT_HOST,LOGIN_HOST,DEAL_HOST,STATICS_URL
from setting_lc import MONTH_URL

class LoginRequest:
    """
     this is a interface , you should imply  callback
    """
    request_header = {
        "Usage-Agent":'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:41.0) Gecko/20100101 Firefox/41.0',
        'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language':'"zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"',
        'Accept-Encoding': 'gzip,deflate',
        'Connection':'keep-alive',
        
    }

    def __init_network_set__(self):
        """
        this function support for cookie and login post " 
        """
        

        cj = cookiejar.LWPCookieJar()
        cookie_support = ur.HTTPCookieProcessor(cj)
        cookie_support_plugin = ur.build_opener(cookie_support)
        ur.install_opener(cookie_support_plugin)

        self.init_response = ur.urlopen(self.init_host)
        #add cookie
        LoginRequest.request_header['Cookie'] = self.init_response.headers.values()[-1].split(";")[0]
        print (" ---    init ok   --- ")
        #print (" cookie : ",LoginRequest.request_header['Cookie'])

        xml = self.get(MONTH_URL)
        parseUeage(xml)
        user_info = None
        
        if self.if_login :
            self.token  = LoginRequest.token_rob(str(self.init_response.read()))
            print (" --- token rob ok --- ")
            print (self.token)
            if not  self.token : self.token = ["test1","test2"]
            # do some encrypt and b64
            
        
            LoginRequest.request_header['__RequestVerificationToken'] = self.token[0]
            user_info = login_encode_type4(self.token[1],user=self.user_name)
        return user_info
        
        
    def __init__(self,hosts,user_name,login=False):
        self.init_host,self.login_host = hosts
        self.if_login = login
        self.user_name = user_name
        LoginRequest.request_header['Referer'] = self.init_host
        self.request = None
        self.response = []
        
        # this is for network setting 
        login_args = self.__init_network_set__()
        if self.if_login:
            print ("login -- args  %s \n: ",login_args)
            # settign login data
            login_data = login_args.encode("utf-8")
            self.request = ur.Request(self.login_host,data=login_data,headers=LoginRequest.request_header)

            self.response = ur.urlopen(self.request)
            self.code = self.response.code

    def urlopen(self,request):
        rs = ur.urlopen(request)
        return rs.read().decode()

    def get(self,deal_host):
        rq = ur.Request(deal_host,headers=self.request_header)
        return self.urlopen(rq)
        
    def post(self,deal_host,callback,**post_args):
        pass


    @staticmethod 
    def token_rob(init_web):
#        re_str = r'(?:<meta\sname=\"csrf_token\"\scontent=\")(\w+?)'
        # this to rob
        re_str = r'(?:<meta(?:.+?)csrf_token(?:.+?)content=)([\S\w].+?)\"'
        tokens = [ i.strip() for i in re.findall(re_str,init_web) ]
        tokens = [ i[1:] for i in tokens if i[0] == '"' ]
        return tokens


if __name__ == "__main__":
    lo = LoginRequest((INIT_HOST,LOGIN_HOST),"admin")
    
